package com.ranga.mselfcare.services;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

import com.ranga.mselfcare.config.Config;

public class BalanceService extends IntentService {
	private static final String TAG = "BalanceService";
	private static final String ID_TOKEN = "Token";
	private static final String ID_MSISDN = "Msisdn";
	private static final String ID_ERROR_CODE = "ErrorCode";
	private String phoneNumber = "";
	private String token = "";
	private Messenger progressMessenger;
	private Messenger resultMessenger;
	private JSONObject responseJSon;
	private int status;
	private String responseString = "";
	
	public BalanceService() {
		super("BalanceService");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		Bundle extras = intent.getExtras();
		Log.i(TAG, getClass().getSimpleName() + "");
		
		if (extras != null) {
			getDataFromPreviousActivity(extras);
		}
		
		status = Config.PROGRESS_STARTED;
		sendProgressMessage(status);
		
		responseJSon = getBalance(phoneNumber, token);
		
		if (status == Config.PROGRESS_STARTED) {
			Log.i(TAG, "finished getting response");
			try {
				if (responseJSon != null && !responseJSon.isNull(ID_ERROR_CODE)) {
					status = Config.PROGRESS_SUCCESS;
					Message message = Message.obtain();
					Bundle bundle = new Bundle();
					bundle.putString(Config.RESPONSE, responseString);
					bundle.putString(Config.RESPONSE_ERROR, responseJSon.getString(ID_ERROR_CODE));
					message.setData(bundle);
					sendResultMessage(message);
					sendProgressMessage(status);
				} else {
					status = Config.PROGRESS_STOPPED;
					sendProgressMessage(status);
				}
			} catch (JSONException e) {
				e.printStackTrace();
				status = Config.PROGRESS_STOPPED;
				sendProgressMessage(status);
			}
			
		}
	}

	private void getDataFromPreviousActivity(Bundle bundle) {
		if (bundle.containsKey(Config.PROGRESS_MESSENGER)) {
			progressMessenger = (Messenger) bundle.get(Config.PROGRESS_MESSENGER);
		}
		if (bundle.containsKey(Config.PHONE_NUMBER)) {
			phoneNumber = bundle.getString(Config.PHONE_NUMBER);
		}
		if (bundle.containsKey(Config.RESULT_MESSENGER)) {
			resultMessenger = (Messenger) bundle.get(Config.RESULT_MESSENGER);
		}
		if (bundle.containsKey(Config.TOKEN)) {
			token = bundle.getString(Config.TOKEN);
		}
		
	}
	
	private void sendResultMessage(Message message) {
		try {
			resultMessenger.send(message);
			status = Config.PROGRESS_SUCCESS;
		} catch (RemoteException e) {
			status = Config.PROGRESS_STOPPED;
			Log.w(TAG, "Exception sending result message", e);
		}
	}
	
	private void sendProgressMessage(int progress) {
		Message message = Message.obtain();
		message.arg1 = progress;
		try {
			progressMessenger.send(message);
		} catch (RemoteException e) {
			Log.w(TAG, "Exception sending progress message", e);
		}
	} 
	
	private JSONObject getBalance(String phoneNumber, String token) {
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost getTokenPost = new HttpPost(Config.REST_ADDRESS + Config.POST_GET_BALANCE);
		getTokenPost.setHeader("Content-type", "application/x-www-form-urlencoded;charset=UTF-8");
		
		ArrayList<NameValuePair> getBalanceParameters = new ArrayList<NameValuePair>(2);
		getBalanceParameters.add(new BasicNameValuePair(ID_MSISDN, phoneNumber)); 
		getBalanceParameters.add(new BasicNameValuePair(ID_TOKEN, token));
		StringBuilder stringBuilder = new StringBuilder();
		JSONObject obj = new JSONObject();		
		 
		try {
			getTokenPost.setEntity(new UrlEncodedFormEntity(getBalanceParameters));
			HttpResponse response = httpClient.execute(getTokenPost);
			
			StatusLine statusLine = response.getStatusLine();
			int resultCode = statusLine.getStatusCode();
		    
		    if (resultCode == 200) {
		    	HttpEntity entity = response.getEntity();
		        InputStream content = entity.getContent();
		       
		        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
		        String line = "";
		        while ((line = reader.readLine()) != null) {
		        	stringBuilder.append(line);
		        }
		        Log.e(TAG, stringBuilder.toString());
		        
		        obj = new JSONObject(stringBuilder.toString());
		        responseString = stringBuilder.toString();
		    } else {
		    	Log.w("result code is not 200", resultCode + "");
				status = Config.PROGRESS_STOPPED;
		    }
		} catch (ClientProtocolException e) {
			Log.w(TAG, "Error Posting getToken"+ e.toString());
			status = Config.PROGRESS_STOPPED;
			sendProgressMessage(status);
		} catch (IOException e) {
			Log.w(TAG, "Error Posting getToken"+ e.toString());
			status = Config.PROGRESS_STOPPED;
			sendProgressMessage(status);
		} catch (JSONException e) {
			Log.w(TAG, "Error Posting getTokent"+ e.toString());
			status = Config.PROGRESS_STOPPED;
			sendProgressMessage(status);
		}
		
		responseString = stringBuilder.toString();
		Log.i(TAG, "Response from server:" + responseString + "");
		return obj;
	}
	
}
